<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Cash;
use Illuminate\Http\Request;

class CashController extends Controller
{
    // 提现列表
    public function index(Request $request)
    {
        $searchData = $request->post();
        $page = $request->post('page', 1);
        $limit = config('app.limit');

        $model = Cash::orderBy('cash.id', 'DESC')
            ->leftJoin('users', 'users.id', '=', 'cash.user_id')
            ->select(['cash.*', 'users.nickname']);

        if ($nickname = $searchData['nickname'] ?? '') {
            $model->where('nickname', 'like', "%{$nickname}%");
        }
        if ($created_at = $searchData['created_at'] ?? []) {
            $model->whereBetween('cash.created_at', $created_at);
        }
        $modelTo = clone $model;
        $status = $searchData['status'] ?? -1;
        if ($status >= 0) {
            $model->where('cash.status', $status);
        } else {
            $model->where('cash.status', 0);
        }

        $result = $model->paginate($limit);

        foreach ($result->items() as $item) {
            $item->createdAt = $item->created_at->format('Y-m-d H:i:s');
        }

        $total = $result->total();
        $items = $result->items();

        if ($status < 0) {
            $modelTo = $modelTo->where('cash.status', '!=', 0);
            $total += $modelTo->count();
            if (count($items) != $limit) {
                // 查询其它状态
                if ($items) {
                    $offset = 0;
                    $limit = $limit - count($items);
                } else {
                    $offset = (($page - 1) * $limit) - $total;
                }

                $list = $modelTo->offset($offset)->limit($limit)->get()->toArray();
                foreach ($list as $k => $value) {
                    $list[$k]['createdAt'] = date('Y-m-d H:i:s', strtotime($value['created_at']));
                }
                $items = array_merge($items, $list);
            }
        }

        return $this->writeJson(0, [
            'data' => $items,
            'count' => $total
        ]);
    }

    // 同意提现
    public function agree(Request $request)
    {
        $id = $request->post('id');

        if (Cash::setStatus($id, 1)) {
            return $this->writeJson(0, null, '操作成功');
        } else {
            return $this->writeJson(500, null, '操作失败');
        }
    }

    // 拒绝提现
    public function reject(Request $request)
    {
        $id = $request->post('id');
        $fail = $request->post('fail');
        if (empty($fail)) {
            return $this->writeJson(500, null, '请输入拒绝原因');
        }

        if (Cash::setStatus($id, 2, $fail)) {
            return $this->writeJson(0, null, '操作成功');
        } else {
            return $this->writeJson(500, null, '操作失败');
        }
    }

}
